package com.its.common.redis.config;

import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;

/**
 * @Author xiaxp
 * @Date 1/14/22 11:12
 * @Description
 *
 * 生产端使用：
 *
 *     @Resource(name = "rDelayedQueue")
 *     private RDelayedQueue<Object> rDelayedQueue;
 *
 *     public void offer() {
 *         rDelayedQueue.offerAsync("task: " + i, 1, TimeUnit.SECONDS);
 *     }
 *
 * 消费端使用：
 * public class TakeTask {
 *
 *     @Resource(name = "rBlockingQueue")
 *     private RBlockingQueue<Object> rBlockingQueue;
 *
 *     @PostConstruct
 *     public void take() {
 *         new Thread(() -> {
 *             while (true) {
 *                 try {
 *                     String s = (String)rBlockingQueue.take();
 *                     System.out.println(s);
 *                 } catch (InterruptedException e) {
 *                     e.printStackTrace();
 *                 }
 *             }
 *         }).start();
 *     }
 * }
 */
@ConditionalOnExpression("${its.redis.enabled:false}&&${its.redis.delayedQueue.enabled:false}")
public class RedissonDelayedQueueConfig {
    private final String queueName = "redis-delay-queue";

    @Bean
    public RBlockingQueue<Object> rBlockingQueue(@Qualifier("redissonClient") RedissonClient redissonClient) {
        return redissonClient.getBlockingQueue(queueName);
    }

    @Bean
    public RDelayedQueue<Object> rDelayedQueue(@Qualifier("redissonClient") RedissonClient redissonClient,
                                               @Qualifier("rBlockingQueue") RBlockingQueue<Object> blockQueue) {
        return redissonClient.getDelayedQueue(blockQueue);
    }
}
